
const { CabinetModel, EquipmentModel  } = require('../../models/index')
const koaTool = require('../../commons/koa_tool')
const _const = require('../../commons/const')
const mqttService = require("../../services/mqtt")
class CabinetController {

    // 数据检验
    saveValid = async (ctx, input) =>{
        return new Promise(async resolve => {
            const {isNull} = require("../../commons/util.js");

            let validKeys = [
                {prop: "name", label: "柜名称"},
                {prop: "code", label: "柜编号"},
                {prop: "volume", label: "柜容量"},
                {prop: "specs", label: "规格"},
                {prop: "cabinet_status", label: "柜子状态"},
                {prop: "enterprise_id", label: "所属企业"},
            ];
    
            let unValidIdx = validKeys.findIndex(item => {
                return isNull(input[item.prop])
            });
            if(unValidIdx != -1){
                koaTool.error(ctx,`${validKeys[unValidIdx].label}不能为空`);
                return resolve(false)
            }
    
            // 设备code不能重复
            let existQuery = {
                code: input.code
            };
            if(input._id){
                existQuery._id = {
                    "$ne": input._id,
                }
            }
            let existEntity = await CabinetModel.findOne(existQuery);
            if(existEntity){
                koaTool.error(ctx,"设备编号已存在，请确认");
                return resolve(false)
            }

            return resolve(true);
        })

    }

    //新增
    create = async (ctx) => {

        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        // 数据检验
        let validRes = await this.saveValid(ctx,input)
        if(!validRes) return;

        let newData = Object.assign({}, input, {
            status: 1
        })

        let cabinetEntity = await CabinetModel.create(newData)

        mqttService.getCabinetData();
        return koaTool.success(ctx,'创建成功');
    }

    //详情
    detail = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        const detail = await CabinetModel.findById(input.id)
        if(detail){
            return koaTool.success(ctx,'获取成功',{
                detail
            });
        }
        mqttService.getCabinetData();
        return koaTool.error(ctx,'无该类目信息');
    }
    //更新
    update = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        let detail = await CabinetModel.findById(input.id)
        if (!detail) {
            return koaTool.error(ctx,"该数据不存在，请检查~");
        }

        // 数据检验
        let validRes = await this.saveValid(ctx,input)
        if(!validRes) return;
        
        let props = ["name","code", "cordon",'specs','volume','type',"enterprise_id","machine_status"];
        props.forEach(prop => {
            if(!isNull(input[prop])){
                detail[prop] = input[prop];
            }
        });
        await detail.save()
        mqttService.getCabinetData();
        return koaTool.success(ctx, '编辑成功');
    }
    //删除
    delete = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }  
 
        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        let detail = await CabinetModel.findById(input.id)
        if (!detail) {
            return koaTool.error(ctx,"数据异常");
        }

        detail.status = 2;  //标记删除

        await detail.save();
        mqttService.getEquipmentData();
        mqttService.getCabinetData();
        return koaTool.success(ctx, '删除成功');
    }
    //列表
    list = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['page'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let {
            page,
            limit,
            code,
            includeEquDetail
        } = ctx.request.query;


        limit = Number(limit)
        page = page || 0
        page = page - 1
        let query = {
            status: 1,
        };


        if (code) {
            const reg = new RegExp(code, 'i') //不区分大小写
            query.$and = query.$and || []
            query.$and.push({
                $or: [
                    {'code': {$regex: reg}},
                ]
            })
        }

        ["enterprise_id","cabinet_status"].forEach(prop => {
            if(ctx.request.query[prop]){
                query[prop] = ctx.request.query[prop]
            }
        })

        let total = await CabinetModel.countDocuments(query)
        let list = await CabinetModel.find(query).populate({path: "enterprise_id",select: "name"}).sort([
            ['create_at',-1],
        ]).skip(page * limit).limit(limit).lean();
        list = list.map(item => {
            item.enterpriseName = item.enterprise_id.name;
            item.enterprise_id = item.enterprise_id._id;
            item.cabinetStatusName = _const.MACHINE_STATUS_MAP[item.cabinet_status];
            return item;
        })

        // 带出柜子中的设备状态
        if(includeEquDetail)
        for(let i = 0; i < list.length; i++){
            let tQuery = {
                cabinet_id: list[i]._id,
                status: 1,
            }
            let equipmentDataList = await EquipmentModel.find(tQuery,'-_id machine_status').lean();
            list[i].equ_count = {
                normal: equipmentDataList.filter(item => item.machine_status == 1).length,
                unnormal: equipmentDataList.filter(item => item.machine_status == 2).length,
                break: equipmentDataList.filter(item => item.machine_status == 3).length,
            } 
        }


        koaTool.succ(ctx, {
            list,
            total
        })
    }

    // 根据企业Id 获取柜数据
    getCabinetByEntId = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ["enterpriseId"])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        };
        if(input.enterpriseId === 'undefined'){
            return koaTool.fail(ctx, "参数缺失")
        }
        let query = {
            enterprise_id: input.enterpriseId,
            status: 1
        }
        let cabinetData = await CabinetModel.find(query).lean();
        let resultData = cabinetData.map(item => {
            return {
                value: item._id,
                label: item.name,
            }
        })

        koaTool.succ(ctx,resultData)

    }

}

module.exports=new CabinetController()

